<template>
  <div style="margin: 50px;display: flex;">
    <div class="menu-list">
      <div v-for="(parentMenu, parentIndex) in menuList" :key="parentMenu.name">
        <MenuItem :itemDate="parentMenu"
                  :onEdit="triggerAction.bind(this, [parentIndex, null], 'edit')"
                  :onDelete="triggerAction.bind(this, [parentIndex, null], 'delete')" />
        <MenuItem v-if="parentMenu.children && parentMenu.children.length > 0"
                  v-for="(childMenu, childIndex) in parentMenu.children"
                  :key="childMenu.name"
                  :isChildMenu="true"
                  :itemDate="childMenu"
                  :onEdit="triggerAction.bind(this, [parentIndex, childIndex], 'edit')"
                  :onDelete="triggerAction.bind(this, [parentIndex, childIndex], 'delete')" />
        <Button class="margin-top_10" type="primary" size="small"
          @click="triggerAction([parentIndex, null], 'add')">新增子菜单</Button>
      </div>
      <Button type="success" class="margin-top_20" style="width: 100%;"
          @click="addFirstClass()">新增一级菜单</Button>
    </div>
    <Form v-if="type !== ''" class="config-container" :model="currentMenu" :rules="ruleValidate" :label-width="100">
      <h3 v-if="type === 'edit'" style="text-align: center;">编辑菜单：{{currentMenu.name}}</h3>
      <h3 v-if="type === 'add' || type === 'addFirstClass'" style="text-align: center;">新增菜单</h3>
      <br />
      <FormItem label="标题: " prop="name">
          <Input v-model="currentMenu.name" style="width: 120px;" />
      </FormItem>
      <FormItem label="访问权限: ">
          <Select v-model="currentMenu.access" style="width: 120px;">
            <Option v-for="item in ACCESS_LIST" :value="item.value" :key="item.value">
              {{ item.label }}
            </Option>
          </Select>
      </FormItem>
      <FormItem label="操作权限 (预留): ">
        <Button type="primary" style="width: 120px;" disabled>编辑</Button>
      </FormItem>
      <FormItem>
        <Button type="success" @click="handleSubmit()">保存</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import MenuItem from './menu-item.vue';

export const ACCESS_LABEL_MAP = {
  'super_admin': '超级管理员',
  'admin': '普通管理员'
};

const ACCESS_ROLEID_MAP = {
  'super_admin': 1,
  'admin': 0
};
const ACCESS_LIST = [{
  label: ACCESS_LABEL_MAP.super_admin,
  value: 'super_admin'
}, {
  label: ACCESS_LABEL_MAP.admin,
  value: 'admin'
}];

export default {
  components: {
    MenuItem
  },
  data () {
    return {
      ACCESS_LIST,
      ACCESS_ROLEID_MAP,
      ACCESS_LABEL_MAP,
      type: '', // edit / add / addFirstClass
      menuList: [{
        name: '项目管理',
        access: 'admin',
        children: [{
          name: '基本信息',
          access: 'admin'
        }, {
          name: '人员管理',
          access: 'super_admin'
        }]
      }, {
        name: '消息管理',
        access: 'admin',
        children: [{
          name: '我的待办',
          access: 'admin'
        }, {
          name: '我的已办',
          access: 'admin'
        }]
      }],
      currentMenu: {
        name: '',
        access: '',
        parentIndex: null,
        childIndex: null
      },
      ruleValidate: {
        name: [{ required: true, message: '标题不能为空', trigger: 'change' }]
      },
      showDialogModal: false
    };
  },
  methods: {
    getTargetMenuItem (parentIndex, childIndex) {
      if (this.type === 'addFirstClass') {
        return {
          name: this.currentMenu.name,
          access: this.currentMenu.access,
          children: []
        };
      }
      return childIndex === null ? this.menuList[parentIndex] : this.menuList[parentIndex].children[childIndex];
    },
    // Confirm the children menu access less than parent menu access
    checkAccessValid (targetMenuItem) {
      const { access, children, parentIndex, childIndex } = targetMenuItem;

      // Have child menu list
      if (childIndex === null) {
        return children.every(childItem => ACCESS_ROLEID_MAP[childItem.access] >= ACCESS_ROLEID_MAP[access]);
      }

      return ACCESS_ROLEID_MAP[access] >= ACCESS_ROLEID_MAP[this.menuList[parentIndex].access];
    },
    // position: [parentIndex, childIndex]
    // type: edit / delete / add
    triggerAction (position, type) {
      const [parentIndex, childIndex] = position;
      const targetMenuItem = this.getTargetMenuItem(parentIndex, childIndex);
      const _menuList = this.menuList;

      if (type === 'edit') {
        this.currentMenu = targetMenuItem ? {
          name: targetMenuItem.name,
          access: targetMenuItem.access,
          parentIndex,
          childIndex
        } : {
          name: '',
          access: '',
          parentIndex: null,
          childIndex: null
        };
        this.type = type;
      }

      if (type === 'delete') {
        this.$Modal.confirm({
          title: '确定要删除该菜单吗？',
          content: '<p>该操作会删除该菜单以及所有的子菜单。</p>',
          onOk: () => {
            if (childIndex === null) {
              _menuList.splice(parentIndex, 1);
            } else {
              _menuList[parentIndex].children.splice(childIndex, 1);
            }

            this.menuList = _menuList;
          }
        });
      }

      if (type === 'add') {
        this.currentMenu = {
          name: '',
          access: '',
          parentIndex,
          childIndex: targetMenuItem.children.length
        };
        this.type = type;
      }
    },
    addFirstClass () {
      this.currentMenu = {
        name: '',
        access: '',
        parentIndex: this.menuList.length,
        childIndex: null
      };
      this.type = 'addFirstClass';
    },
    handleSubmit () {
      const { name, access, parentIndex, childIndex } = this.currentMenu;
      const targetMenuItem = this.getTargetMenuItem(parentIndex, childIndex);

      if (!name) {
        this.$Modal.error({
          title: '提醒',
          content: '标题不能为空'
        });
        return void 0;
      }

      if (!this.checkAccessValid({
        ...targetMenuItem,
        ...this.currentMenu
      }, [parentIndex, childIndex])) {
        this.$Modal.error({
          title: '提醒',
          content: '子菜单的访问权限不能小于父级菜单'
        });
        return void 0;
      }

      if (this.type === 'edit') {
        // Update target menu item
        targetMenuItem.name = name;
        targetMenuItem.access = access;
      } else if (this.type === 'add') {
        this.menuList[parentIndex].children.push({
          name,
          access
        });
      } else if (this.type === 'addFirstClass') {
        this.menuList.push({
          name,
          access,
          children: []
        });
      }

      this.$Modal.success({
        title: '提醒',
        content: '保存成功'
      });
      this.type = '';

      console.log(this.menuList);
    }
  }
};
</script>

<style lang="less" scoped>
  .margin-top_10 {
    margin-top: 10px;
  }
  .margin-top_20 {
    margin-top: 20px;
  }

  .menu-list {
    width: 250px;
    max-height: 800px;
    overflow-y: auto;
  }
  .config-container {
    width: 200px;
    margin-left: 100px;
    padding-top: 10px;
  }
</style>
